package com.jj.spb.spring_boot_mybatis.service;

import com.jj.spb.spring_boot_mybatis.entity.Student;
import com.jj.spb.spring_boot_mybatis.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class StudentJPAService {

    @Autowired
    StudentRepository repository;

    public Student findById(int id){
        Optional<Student> student = repository.findById(id);
        if(student.isPresent()){
            return student.get();
        }
        return null;
    }

    /**
     * 保存/更新 Student
     * @param student
     * @return  id , if == 0, false
     */
    public int saveStudent(Student student){
        if(student.getId() != 0 && repository.existsById(student.getId())){
            student = repository.save(student);
            return student.getId();
        }
        else{
            student.setId(getIdByStudyNum(student.getStudyNum()));
            repository.save(student);
            return getIdByStudyNum(student.getStudyNum());
        }
    }

    public int getIdByStudyNum(int studyNum){
        Optional<Integer> idOptional = repository.findIdByStudyNum(studyNum);
        if(idOptional.isPresent()){
            return idOptional.get();
        }
        return 0;
    }
}
